import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqUserLogOut } from '../../api/user/index'
import { loginParam } from '../../api/user/type'
import type { IUserCtx } from './types'
import routes from '../../router/routes'
import { asyncRoutes, anyRoutes } from '../../router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
function filterRoute(asyncRoutes: any[], routes: string[]) {
  return asyncRoutes.filter((item) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoute(item.children, routes)
        console.log(item.children)
      }
      return true
    }
  })
}
export default defineStore('user', {
  state: (): IUserCtx => {
    return {
      token: localStorage.getItem('TOKEN'),
      routes: routes,
      avatar: '',
      username: '',
      buttons: [],
    }
  },
  actions: {
    async userLogin(loginForm: loginParam) {
      const response = await reqLogin(loginForm)
      if (response.code == 200) {
        const token = response.data
        this.token = token
        console.log(token)
        localStorage.setItem('TOKEN', token)
        return 'ok'
      } else {
        throw '错误'
      }
    },
    async requestUserInfo() {
      let result = await reqUserInfo()
      console.log(result)
      if (result.code == 200) {
        this.avatar = result.data.avatar
        this.username = result.data.name
        this.buttons = result.data.buttons
        console.log(asyncRoutes)

        let userRoutes = filterRoute(cloneDeep(asyncRoutes), result.data.routes)
        console.log(result.data.routes)
        console.log(userRoutes)

        this.routes = [...routes, ...userRoutes, ...anyRoutes]
        console.log(this.routes)
        ;[...userRoutes, ...anyRoutes].forEach((route) => {
          router.addRoute(route)
        })
      }
    },
    async exitLogin() {
      try {
        let result = await reqUserLogOut({ token: this.token })
        if (result.code == 200) {
          this.token = ''
          this.avatar = ''
          this.username = ''
          localStorage.removeItem('TOKEN')
          return 'ok'
        } else {
          throw '错误'
        }
      } catch (error) {}
    },
  },
})
